import 'dart:collection';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_syt/domain/widgets/photo_views_more_screen.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/fade_route.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/loading_widget.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "webInView")
class WebVideoPage extends StatefulWidget {
  final String url;
  String title;
  final bool needBar;

  // final bool showShare;
  bool openCheckPhotos;
  final Function(String title)? titleCall;

// bool needBar = true;
  // bool isUseUserAgent = false;
  // bool needLongpressSave = true;
  // final Function(String title)? titleCall;
  // var currentJson = Map<String, String>(); //当前执行的JS事件参数
  // WebDetailPage(this.url, {this.titleCall});

  WebVideoPage(this.url,
      {this.needBar = true,
      this.title = '',
      this.titleCall,
      // this.showShare = false,
      this.openCheckPhotos = true});

  @override
  WebVideoPageState createState() => WebVideoPageState();
}

class WebVideoPageState extends State<WebVideoPage> {
  // String _title = '';
  // bool _loadComplete = false;
  // String _url = '';
  bool isLoading = true;

  // bool isGetTitle = false;
  String? _error;
  TapDownDetails? _downDetailsPress;
  bool isLongGes = false;
  InAppWebViewController? _webViewController;
  double progress = 0;
  // bool showSave = false;

  // InAppWebViewSettings options = InAppWebViewSettings(
  //     crossPlatform: InAppWebViewOptions(
  //         useShouldOverrideUrlLoading: true,
  //         mediaPlaybackRequiresUserGesture: false),
  //     android: AndroidInAppWebViewOptions(
  //       useHybridComposition: true,
  //     ),
  //     ios: IOSInAppWebViewOptions(
  //       // isPagingEnabled: true,
  //       allowsInlineMediaPlayback: true,
  //     ));

  InAppWebViewSettings options = InAppWebViewSettings(
    // useShouldOverrideUrlLoading: true,
    // mediaPlaybackRequiresUserGesture: false,
    allowsInlineMediaPlayback: true,
    useHybridComposition: true,
    javaScriptEnabled: true,

    // javaScriptEnabled: true, // 确保 JS 是开的，很多点击事件依赖 JS
    // useHybridComposition: true, // Android 特别重要，避免手势冲突
    // transparentBackground: false,
    // 如果背景透明，容易导致点不到
    // disableContextMenu: false,
    // 是否禁用长按菜单，通常不影响点击
    // supportZoom: false, // 有些时候 zoom 会影响交互，可以先关掉试试看
  );

  Future<void> restoreWebView() async {
    await Future.delayed(const Duration(milliseconds: 300));
    if (_webViewController != null) {
      try {
        // 模拟点击来激活它（很 hack，但有效）
        await _webViewController!.evaluateJavascript(
          source: "document.body.focus();",
        );
        await _webViewController!.requestFocus();
      } catch (e) {
        print("恢复 WebView 失败：$e");
      }
    }
  }

  InAppWebView? _inAppWebView;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: widget.needBar
            ? AppBar(
                titleSpacing: 0.0,
                // elevation: 1,
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: ClickUtils.debounce(() => {_back()}),
                    ),
                    IconButton(
                      icon: Icon(Icons.close),
                      onPressed: ClickUtils.debounce(() => {_closePage()}),
                    ),
                    Expanded(
                      child: Center(child: Text(widget.title)),
                    ),
                    Container(width: 96, height: 40),
                  ],
                ),
                automaticallyImplyLeading: false,
                centerTitle: true,
              )
            : null,
        body: SizedBox(
          width: 1.sw,
          height: 1.sh,
          // color: Colors.red,
          child: Stack(
            children: [
              // Positioned.fill(
              //     child: widget.openCheckPhotos
              //         ? GestureDetector(
              //             onTapDown: (details) {
              //               _downDetailsPress = details;
              //             },
              //             onLongPress: () async {
              //               isLongGes = false;
              //               if (_downDetailsPress != null &&
              //                   isLoading == false) {
              //                 if (_webViewController != null) {
              //                   // _downDetailsPress?
              //                   // String imgUrlScript =
              //                   //     'var element = document.elementFromPoint(${_downDetailsPress?.localPosition.dx}, ${_downDetailsPress?.localPosition.dy});'
              //                   //     'element ? element.src : null;';
              //                   // var value = await _webViewController!
              //                   //     .evaluateJavascript(source: imgUrlScript);
              //
              //                   DLog('我获取到了long====  $_downDetailsPress');
              //
              //                   // if (value != '(null)' &&
              //                   //     value.isNotEmpty &&
              //                   //     value != 'null' &&
              //                   //     value.length > 10) {
              //                     // await UtilsOther.showPopupMeun(
              //                     //     _downDetailsPress!.globalPosition,
              //                     //     value,
              //                     //     context);
              //                     //
              //                     // setState(() {
              //                     //   // showSave = true;
              //                     // });
              //
              //                     // UtilsOther.showOverlay(context,
              //                     //     _downDetailsPress!.globalPosition, value);
              //                     // await Future.delayed(Duration(milliseconds: 100));
              //                     // _webViewController?.requestFocus();
              //                     await restoreWebView();
              //
              //                     // _webViewController?.requestFocus();
              //                   // }
              //                 }
              //               }
              //             },
              //             child: _buildWebView())
              //         : _buildWebView()),

              Positioned.fill(child: _buildWebView()),

              // Positioned.fill(
              //     child: GestureDetector(
              //         onTapDown: (details) {
              //           DLog('onTapDown');
              //           _downDetailsPress = details;
              //         },
              //         onTap: () {}, // 拦截事件避免被底部弹窗遮挡
              //         child: _buildWebView())),
              Positioned.fill(
                  child: IgnorePointer(
                child: Visibility(
                  visible: isLoading,
                  child: Container(
                    // width: 1.sw,
                    // height: 1.sh,

                    color: Colors.white,
                    alignment: Alignment.center,
                    child: const LoadingWidget(),
                  ),
                ),
              )),
              Positioned.fill(
                  child: Visibility(
                      visible: _error != null,
                      child: Container(
                        color: Colors.white,
                        child: TextButton(
                          child: ViewStateEmptyWidget(
                            message: _error != null ? "$_error" : null,
                          ),
                          onPressed: ClickUtils.debounce(() async {
                            // _loadingGetData();
                            if (mounted) {
                              setState(() {
                                isLoading = true;
                                _error = null;
                              });
                            }
                            if (Platform.isIOS) {
                              _webViewController?.loadUrl(
                                  urlRequest: URLRequest(
                                      url: WebUri.uri(Uri.parse(widget.url))));
                            } else {
                              _webViewController?.reload();
                            }
                          }),
                        ),
                      ))),
              progress < 1.0
                  ? LinearProgressIndicator(value: progress)
                  : Container(),
            ],
          ),
        ));
  }

  Widget _buildWebView() {
    _inAppWebView ??= InAppWebView(
      initialUrlRequest: URLRequest(url: WebUri(widget.url)),
      onWebViewCreated: (InAppWebViewController controller) {
        _webViewController = controller;
        controller.addJavaScriptHandler(
          handlerName: "checkFullSize",
          callback: (arguments) {
            DLog("arguments + $arguments");
            if (arguments.isNotEmpty) {
              Map<String, dynamic> json = arguments.first;
              if (json.keys.contains('urls')) {
                List<String> lists = [];
                json['urls'].forEach((element) {
                  lists.add(element.toString());
                });
                Navigator.of(context).push(
                  FadeRoute(
                      page: PhotoViewMoreScreen(
                    imageRows: lists,
                    defaultImage: json['default'] is int
                        ? json['default']
                        : (int.tryParse(json['default']) ?? 0),
                  )),
                );
              }
            }
          },
        );
      },
      onProgressChanged: (controller, progress) {
        if (mounted) {
          setState(() {
            this.progress = progress / 100;
          });
        }

        DLog('asdasd  onProgressChanged  ${this.progress}');
      },
      onReceivedError: (InAppWebViewController controller,
          WebResourceRequest request, WebResourceError error) {
        DLog('asdasd  onReceivedError  ${error.type}');
        // customShowToast(error.type.toString());
        if (mounted &&
            isLoading &&
            error.type != WebResourceErrorType.UNKNOWN &&
            error.type != WebResourceErrorType.HOST_LOOKUP &&
            error.type != WebResourceErrorType.CANNOT_CONNECT_TO_HOST) {
          if (mounted) {
            setState(() {
              isLoading = false;
              _error = S().load_failed;
            });
          }
        }
      },
      onConsoleMessage:
          (InAppWebViewController controller, ConsoleMessage message) {
        DLog('onConsoleMessage  ${message.message}');
      },
      onLoadStop: (controller, url) async {
        DLog('asdasd    onLoadStop');
        if (mounted) {
          setState(() {
            _error = null;
            isLoading = false;
          });
        }
        if (widget.titleCall != null) {
          String? title = await _webViewController?.getTitle();
          DLog(title);
          widget.titleCall!.call(title ?? '');
          if (title != null) {
            if (mounted) {
              setState(() {
                widget.title = title;
              });
            }
          }
        }
      },
      initialSettings: options,
      onPermissionRequest:
          (InAppWebViewController controller, PermissionRequest request) async {
        return PermissionResponse(
            resources: request.resources,
            action: PermissionResponseAction.GRANT);
      },
    );
    return _inAppWebView!;
  }

  void _closePage() {
    // DLog('close page');
    Navigator.pop(context);
    // if (Navigator.canPop(context)) {
    //   Navigator.pop(context);
    // }
  }

  void _back() async {
    var can = await _webViewController?.canGoBack();
    if (can == true) {
      _webViewController?.goBack();
    } else {
      _closePage();
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // 确保在主线程上执行清理操作
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_webViewController != null) {
        _webViewController?.dispose();
        DLog('dispose -web_video_page');
      }
    });
    super.dispose();
  }

  @override
  void didUpdateWidget(WebVideoPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

//  showBottom(BuildContext context,
//     {required String imageUrl,}) async {
//   var item = [
//     S.of(context).map_amap,
//     S.of(context).map_baidu,
//     S.of(context).map_tencent
//   ];
//   if (Platform.isIOS) {
//     item.add(S.of(context).map_apple);
//   }
//   return showModalBottomSheet(
//     shape: RoundedRectangleBorder(
//         borderRadius: BorderRadius.only(
//           topLeft: Radius.circular(8),
//           topRight: Radius.circular(8),
//         )),
//     isScrollControlled: true,
//     context: context,
//     builder: (BuildContext context) {
//       return ListView.separated(
//         separatorBuilder: (context, index) {
//           return Divider(
//             height: 1,
//             color: ThemeColor.colorBlack40,
//           );
//         },
//         shrinkWrap: true,
//         itemCount: item.length,
//         itemBuilder: (BuildContext context, int index) {
//           return ListTile(
//               title: Center(
//                 child: Text(
//                   item[index],
//                   style: TextStyle(
//                     fontSize: 14,
//                     color: ThemeColor.colorBlack100,
//                   ),
//                 ),
//               ),
//               onTap: ClickUtils.debounce(
//                     () {
//                   if (item[index] == S.of(context).map_apple) {
//                     MapNavigatorUtil.gotoAppleMap(
//                         longitude: longitude,
//                         latitude: latitude,
//                         toInstallCallBack: () {
//                           customShowToast(S
//                               .of(context)
//                               .map_mapInstall(S.of(context).map_apple));
//                         });
//                   } else if (item[index] == S.of(context).map_amap) {
//                     MapNavigatorUtil.gotoAMap(
//                         longitude: longitude,
//                         latitude: latitude,
//                         toInstallCallBack: () {
//                           customShowToast(S
//                               .of(context)
//                               .map_mapInstall(S.of(context).map_amap));
//                         });
//                   } else if (item[index] == S.of(context).map_baidu) {
//                     MapNavigatorUtil.gotoBaiduMap(
//                         longitude: longitude,
//                         latitude: latitude,
//                         toInstallCallBack: () {
//                           customShowToast(S
//                               .of(context)
//                               .map_mapInstall(S.of(context).map_baidu));
//                         });
//                   } else if (item[index] == S.of(context).map_tencent) {
//                     MapNavigatorUtil.gotoTencentMap(
//                         longitude: longitude,
//                         latitude: latitude,
//                         toInstallCallBack: () {
//                           customShowToast(S
//                               .of(context)
//                               .map_mapInstall(S.of(context).map_tencent));
//                         });
//                   }
//                 },
//               ));
//         },
//       );
//     },
//   );
// }
}
